//
//  RBWKWebViewController.m
//  RMMaterialRed
//
//  Created by XBWH on 2024/3/6.
//

#import "RBWKWebViewController.h"

@interface RBWKWebViewController ()<WKNavigationDelegate,WKUIDelegate, UIScrollViewDelegate>

@end

@implementation RBWKWebViewController

-(instancetype)init{
    self = [super init];
    if (self) {
        self.firstLoad = YES;
        self.navigationBarHidden = NO;
    }
    return self;
}
- (instancetype)initWithOriginalURLPath:(NSString *)urlPath{
    self = [super init];
    if (self) {
        self.firstLoad = YES;
        self.originalURL = [NSURL URLWithString:urlPath];
        self.navigationBarHidden = NO;
    }
    return self;
}
- (instancetype)initWithHTMLFilePath:(NSURL *)htmlFilePath;{
    self = [super init];
    if (self) {
        self.firstLoad = YES;
        self.htmlFileURL = htmlFilePath;
        self.navigationBarHidden = NO;
    }
    return self;
}
- (void )rb_changeHeight:(CGFloat)height{
    MJWeakSelf
    [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top);
        make.leading.equalTo(weakSelf.view.mas_leading);
        make.trailing.equalTo(weakSelf.view.mas_trailing);
        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-height);
    }];
    [self.view layoutIfNeeded];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (@available(iOS 13.0, *)) {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    }
    [self.navigationController setNavigationBarHidden:self.navigationBarHidden animated:animated];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName :RBHexColor(@"#1A1F28")};
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(rb_handleKeyboardWillChangeFrameNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(rb_handleKeyboardWillChangeFrameNotification:)
                                                 name:UIKeyboardWillChangeFrameNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(rb_handleKeyboardWillHideNotification:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    if (self.originalURL){
        [self.webView loadRequest:[NSURLRequest requestWithURL:self.originalURL]];
    }
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.webView loadRequest:[NSURLRequest requestWithURL:self.originalURL]];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
   
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    self.view.backgroundColor = RBColor(245, 245, 245);
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    
    [self rb_initLayoutViewmake];
    
    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
}
-(void)setHtmlFileURL:(NSURL *)htmlFileURL{
    _htmlFileURL=htmlFileURL;
    [self.webView loadFileURL:htmlFileURL allowingReadAccessToURL:htmlFileURL];
}
-(void)setOriginalURL:(NSURL *)originalURL{
    _originalURL = originalURL;
    [self.webView loadRequest:[NSURLRequest requestWithURL:originalURL]];
}

-(void)rb_initLayoutViewmake{
    CGFloat webViewTop = RBNAVIGATION_BAR_HEIGHT;
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(webViewTop);
        make.left.bottom.right.mas_equalTo(0);
    }];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(webViewTop);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(2);
    }];
}
- (void)rb_handleKeyboardWillChangeFrameNotification:(NSNotification *)notification{
    NSDictionary *keyboardFrameInfo = notification.userInfo;
    CGRect keyboardFrame = [[keyboardFrameInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration = [[keyboardFrameInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSUInteger curve = [[keyboardFrameInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
    CGFloat webViewTop = RBNAVIGATION_BAR_HEIGHT;
    MJWeakSelf
    [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(webViewTop);
        make.leading.equalTo(weakSelf.view.mas_leading);
        make.trailing.equalTo(weakSelf.view.mas_trailing);
        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-keyboardFrame.size.height);
    }];
    [UIView animateWithDuration:duration delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | curve animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
    }];
}

- (void)rb_handleKeyboardWillHideNotification:(NSNotification *)notification{
    NSDictionary *keyboardFrameInfo = notification.userInfo;
    CGFloat duration = [[keyboardFrameInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSUInteger curve = [[keyboardFrameInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
    CGFloat webViewTop = RBNAVIGATION_BAR_HEIGHT;
    MJWeakSelf
    [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(webViewTop);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    [UIView animateWithDuration:duration delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | curve animations:^{
        [weakSelf.view layoutIfNeeded];
    } completion:^(BOOL finished) {
    }];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    MJWeakSelf
    if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView){
        if (self.webView.estimatedProgress >= 0.99f){
            [UIView animateWithDuration:0.3f delay:0.25f options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState animations:^{
                weakSelf.progressView.alpha = 0.0f;
                weakSelf.progressView.progress = self.webView.estimatedProgress;
            } completion:^(BOOL finished) {
                weakSelf.progressView.progress = 0.0f;
            }];
        }else{
            [UIView animateWithDuration:0.3f delay:0.0f options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState animations:^{
                weakSelf.progressView.alpha = 1.0f;
                weakSelf.progressView.progress = self.webView.estimatedProgress;
            } completion:^(BOOL finished) {
                if (weakSelf.firstLoad){
                    weakSelf.firstLoad = NO;
                }
            }];
        }
    }else if ([keyPath isEqualToString:@"title"] && object == self.webView){
        self.title = self.webView.title;
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
}
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if(!navigationAction.targetFrame.isMainFrame){
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

- (WKWebView *)webView{
    if (!_webView){
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero];
        _webView.scrollView.bounces = NO;
        _webView.navigationDelegate = self;
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.delegate = self;
    }
    return _webView;
}

- (UIProgressView *)progressView{
    if (!_progressView){
        _progressView = [[UIProgressView alloc] init];
        _progressView.progressTintColor = RBColor(242, 48, 48);
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}


- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
@end
